// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

var LoginManager = require('LoginManager')
var ClickManager = require('ClickManager')

// 模态框登录
cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
        login: cc.Node,
        loading: cc.Node,

        tips: cc.Node,
        phone: cc.EditBox,
        password: cc.EditBox,

        tipsAnimations: cc.AnimationClip
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        var tips = this.tips.getComponent(cc.Label)

        // this.phone.string = '13885578655'
        // this.password.string = '123123'

        ClickManager.onClick(this.login, this, () => {
            this.loading.active = true
            console.log(this.formData())
            LoginManager.login(this.formData(), (res) => {
                this.loading.active = false
                tips.string = res.msg
                if (res.code !== 200) {
                    this.tips.color = new cc.Color(255, 0, 0)
                    this.doTips()
                } else {
                    this.tips.color = new cc.Color(0, 153, 102)
                    this.tips.active = true
                    cc.sys.localStorage.setItem('__USERSTRING__', JSON.stringify(this.formData()))
                    cc.sys.localStorage.setItem('__TOKEN__', res['data']['token'])
                    cc.director.loadScene('loading')
                }
            })
        })
    },

    start () {

    },

    // 表单数据
    formData () {
        var obj = {
            phone: this.phone.string,
            password: this.password.string
        }

        return obj
    },

    // 信息提示
    doTips () {
        let tipsAnim = this.tips.addComponent(cc.Animation)
        tipsAnim.addClip(this.tipsAnimations, 'tipsAnim')

        this.tips.active = true
        tipsAnim.play('tipsAnim')
    }

    // update (dt) {},
});
